<template>
  <div>
    <el-row :gutter="20">
        <el-col :span="4">
            <div class="nav">
                <div class="nav-title">
                   产品类型列表
                </div>
                <tree-product @sendNodedData="sendNodedData"></tree-product> <!--子组件中触发该事件-->
            </div>
        </el-col>
        <el-col :span="20">
            <div class="wrapper">
                <div class="wrapper-title">
                    {{optionType}}产品
                </div>
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" size="small" class="demo-ruleForm">
                    <el-form-item label="所属分类" prop="category">
                        <span>{{ this.ruleForm.category }}</span>
                    </el-form-item>
                    <el-form-item label="商品名称" prop="title">
                        <el-input v-model="ruleForm.title"></el-input>
                    </el-form-item>
                    <el-form-item label="商品价格" prop="price">
                        <el-input v-model="ruleForm.price"></el-input>
                    </el-form-item>
                    <el-form-item label="商品数量" prop="num">
                        <el-input v-model="ruleForm.num"></el-input>
                    </el-form-item>
                     <el-form-item label="商品卖点" prop="sellPoint">
                        <el-input v-model="ruleForm.sellPoint"></el-input>
                    </el-form-item>
                     <el-form-item label="商品图片" prop="image">
                        <upload-img @sendImgUrl="sendImgUrl" :fileList="fileList"></upload-img><!--当文件上传成功之后服务器会生成一个图片地址保存在一个图片列表中-->
                    </el-form-item>
                    <el-form-item label="商品描述" prop="descs">
                         <wang-editor @sendWangEditor="sendWangEditor" :WangEditorData="WangEditorData" ref="WangEditor"></wang-editor>
                    </el-form-item>

                    <el-form-item label="首页轮播推送" prop="delivery">
                        <el-switch v-model="ruleForm.delivery"  active-color="#13ce66" inactive-color="#ff4949"></el-switch>
                    </el-form-item>

                    <el-form-item label="活动名称" prop="name">
                        <el-input v-model="ruleForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="活动区域" prop="region">
                        <el-select v-model="ruleForm.region" placeholder="请选择活动区域">
                        <el-option label="区域一" value="shanghai"></el-option>
                        <el-option label="区域二" value="beijing"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="活动时间" required>
                        <el-col :span="11">
                        <el-form-item prop="date1">
                            <el-date-picker type="date" placeholder="选择日期" v-model="ruleForm.date1" style="width: 100%;"></el-date-picker>
                        </el-form-item>
                        </el-col>
                        <el-col class="line" :span="2">-</el-col>
                        <el-col :span="11">
                        <el-form-item prop="date2">
                            <el-time-picker placeholder="选择时间" v-model="ruleForm.date2" style="width: 100%;"></el-time-picker>
                        </el-form-item>
                        </el-col>
                    </el-form-item>
                    <el-form-item label="即时配送" prop="delivery">
                        <el-switch v-model="ruleForm.delivery"></el-switch>
                    </el-form-item>
                    <el-form-item label="活动性质" prop="type">
                        <el-checkbox-group v-model="ruleForm.type">
                        <el-checkbox label="美食/餐厅线上活动" name="type"></el-checkbox>
                        <el-checkbox label="地推活动" name="type"></el-checkbox>
                        <el-checkbox label="线下主题活动" name="type"></el-checkbox>
                        <el-checkbox label="单纯品牌曝光" name="type"></el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                    <el-form-item label="特殊资源" prop="resource">
                        <el-radio-group v-model="ruleForm.resource">
                        <el-radio label="线上品牌商赞助"></el-radio>
                        <el-radio label="线下场地免费"></el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="活动形式" prop="desc">
                        <el-input type="textarea" v-model="ruleForm.desc"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" v-if="this.optionType!='详情'" size="small" @click="submitForm('ruleForm') ">保存</el-button>
                        <el-button size="small" v-if="this.optionType!='详情'" @click="resetForm('ruleForm')">重置</el-button>
                        <el-button size="small" @click="goProductList($event)">返回到商品列表</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-col>
    </el-row>
  </div>
</template>

<script>
import TreeProduct from '@/components/TreeItem.vue'
import UploadImg from '@/components/UploadImg.vue'
import WangEditor from '@/components/WangEditor.vue'
import { mapState } from 'vuex';
export default {
    components:{
        TreeProduct,  //组件使用时可以为<tree-product></tree-product>
        UploadImg,  //图片上传组件
        WangEditor
    },
     data() {
      return {
        WangEditorData:'',
        optionType:'',
        fileList:[],
        ruleForm: {
          category: '',
          title:'',
          cid:'',
          price:'',
          num:'',
          sellPoint:'',
          image:[],
          descs:'',
          region: '',
          date1: '',
          date2: '',
          delivery: false,
          type: [],
          resource: '',
          desc: ''
        },
        rules: {  //用于定义字段的校验规则
          category: [
            { required: true, message: '请输入商品类别', trigger: 'blur' },
            { min: 2, max:5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          title: [
            { required: true, message: '请输入商品名称', trigger: 'blur' },
            { min: 3, max: 40, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
           price: [
            { required: true, message: '请输入商品价格', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
           num: [                                                                                                                                                                                                            
            { required: true, message: '请输入商品数量', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ], 
        //   region: [
        //     { required: true, message: '请选择活动区域', trigger: 'change' }
        //   ],
        //   date1: [
        //     { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
        //   ],
        //   date2: [
        //     { type: 'date', required: true, message: '请选择时间', trigger: 'change' }
        //   ],
        //   type: [
        //     { type: 'array', required: true, message: '请至少选择一个活动性质', trigger: 'change' }
        //   ],
        //   resource: [
        //     { required: true, message: '请选择活动资源', trigger: 'change' }
        //   ],
        //   desc: [
        //     { required: true, message: '请填写活动形式', trigger: 'blur' }
        //   ]
        }
      };
    },
    computed:{
        ...mapState('goods',['title','goodsData'])
    },
    //获取store中的数据进行回显
    mounted(){
      this.optionType = this.title
      if(this.title === "编辑" || this.title === "详情"){
        this.ruleForm = {...this.goodsData}  //ruleForm为深拷贝的地址和goodsData不共用地址
        console.log("this.goodsData",this.goodsData)
        //回显图片数据 需要通过AddProduc将链接数据传递给 UploadImg组件
        console.log("this.goodsData.image",this.goodsData.image)
          let imgs = JSON.parse(this.goodsData.image)
          this.ruleForm.image = imgs
          console.log("解析后的imgs信息",imgs)
          let arr =[]
          imgs.forEach(element => {
            let obj={}
            obj.url = element
            arr.push(obj)
          });
        this.fileList = arr
        //回显富文本编辑器的数据
        this.WangEditorData = this.goodsData.descs
        console.log(this.WangEditorData)
        }
      },
    // },
    methods: {
      sendImgUrl(val){
         console.log("图片上传组件传递过来的图片Url为",val)
         this.ruleForm.image.push(val)  //用于图片的回显

      },
      //点击返回到商品列表
      goProductList(event){
        console.log("点击返回到商品列表按钮事件被触发",event)
        this.$router.push('/product/productlist') //跳转到商品列表
      },
      sendNodedData(val){
        this.ruleForm.category = val.name
        this.ruleForm.cid = val.cid
      },
      // 编辑页面和新增页面共用 保存按钮,编辑页面点击调用数据库更新操作，而新增调用数据库添加操作
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            //alert('submit!');
            //获取表单的数据并调用后台的接口插入数据 
            console.log("收集到表单数据:",JSON.stringify(this.ruleForm))  //title cid  category sellPoint price num descs paramsInfo image
            let {id,title,cid ,category, sellPoint ,price, num, descs, image} = this.ruleForm
            //this.insertProduct({title, cid,  category, sellPoint, price, num, descs,image:JSON.stringify(image)})
            console.log("image",JSON.stringify(image))
            if(this.optionType === "新增"){
               this.insertProduct({title, cid,  category, sellPoint, price, num, descs,image:JSON.stringify(image)})
            }else if(this.optionType === "编辑"){
               this.updateProduct({id,title, cid,  category, sellPoint, price, num, descs,image:JSON.stringify(image)})
            }
            
          } else {
            console.log('数据校验未通过');
            return false;
          }
        });
      },
      /***
       * 重置表单数据方式1：
       * 重置表单数据 element-ui提供的重置表单的方法 this.$refs[formName].resetFields()只能清除通过prop渲染的数据
       *  1.清除数据可以使用element-ui组件提供的原生的方法
       *  2.也可以通过手动将数据置空操作达到清空数据的目的
       * 
       * 重置按钮分为两种情况，
       *   1.编辑产品时的重置，相当于将数据恢复到vue仓库中的数据
       *   2.新增产品时的重置，相当于将表单置空
       */
      resetForm1(formName) {
        // 只能清除通过prop渲染的数据
        this.$refs[formName].resetFields();
        //清空通过upload渲染的图片
        this.fileList = []
        //清空wangEditor渲染的富文本数据，wangeditor默认值html的值为空字符串,设置一个空格才能被wangeditor检测到数据的变化
        this.WangEditorData =' '
      },
       //重置表单数据方式2：
       resetForm(formName) {
        if("编辑" === this.optionType){
          //方式1：直接通过路由控制页面重新刷新
          //this.$router.push('/product/productlist') //跳转页面

          //方式2：不进行页面跳转只进行数据䣌更新操作
          this.ruleForm = {...this.goodsData} //将表单数据恢复到vuex中的数据
          let imgs = JSON.parse(this.goodsData.image)
          this.ruleForm.image = imgs
          console.log("解析后的imgs信息",imgs)
          let arr =[]
          imgs.forEach(element => {
            let obj={}
            obj.url = element
            arr.push(obj)
          });
        this.fileList = arr
        //回显富文本编辑器的数据
        //this.WangEditorData = this.goodsData.descs //数据未修改不能被wangEditor监控到
        this.$refs.WangEditor.editor.setHtml(this.goodsData.descs)
        console.log(this.WangEditorData)
        }else{
          // 只能清除通过prop渲染的数据
          this.$refs[formName].resetFields();
          //清空通过upload渲染的图片
          this.fileList = []
          //清空wangEditor渲染的富文本数据
          console.log("调用WangEditor组件中的清空方法,获取到自定义方法", this.$refs.WangEditor)
          this.$refs.WangEditor.clearEditor() //调用WangEditor组件中的清空方法
        }
      },
      sendWangEditor(edit){
        console.log("获取到富文本编辑器的数据:",edit)
        this.ruleForm.descs = edit
      },
      async insertProduct(params){
        let res = await this.$api.addProduct(params)
        console.log("添加商品-------",res.data)
        if(res.data.status === 200){
          this.$message({
            message:"恭喜您，商品添加成功",
            type:'success'
          })
          this.$router.push('/product/productlist')
        }
        
      },
      async updateProduct(params){
       let res =  await this.$api.updateProduct(params)
        console.log("修改商品-------",res.data)
         if(res.data.status === 200){
          this.$message({
            message:"恭喜您，商品修改成功",
            type:'success'
          })
          
        }
        this.$router.push('/product/productlist')
      }

    }
}
</script>

<style lang="less" scoped>
    .nav{
        background-color: #eee;
        height: 700px;
        .nav-title{
            color: #fff;
            background-color: skyblue;
            padding:20px
        }
    }
    .wrapper{
        background-color: #eee;
        height: 1300px;
        .wrapper-title{
            color: #000; 
            background-color: #ccc;
            padding: 14px;
            margin-bottom: 20px;
        }
    }
    .demo-ruleForm{
        padding:30px
    }
</style>